package com.devframe.srtp.server.file;

import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.netty.handler.codec.http.multipart.FileUpload;

import com.devframe.srtp.Account;
import com.devframe.srtp.SRTPConstants;
import com.devframe.srtp.SRTPResult;
import com.devframe.srtp.server.parse.SRTPParam;
import com.devframe.srtp.util.common.SRTPThumbUtil;

/**
 * 文件存储
 * @author 詹保山
 *
 *yyMMddhhmiss_xxxxx.jpg
 */
public class SRTPStoreFileHandler {
	
	private static Log log=LogFactory.getLog(SRTPStoreFileHandler.class);
	
	private Account account;
	/**
	 * 文件名
	 */
	private String fileName;
	/**
	 * 目录路径
	 */
	private String dirPath;
	/**
	 * 保存路径，去除掉根目录
	 */
	private String savePath;
	/**
	 * 产生文件名
	 * @param fileName
	 * @return
	 */
	private  String generateFileNameOfTime(String fileName) {
		DateFormat format = new SimpleDateFormat("yyMMddHHmmss");
		String formatDate = format.format(new Date());
		int random = new Random().nextInt(10000);
		int position = fileName.lastIndexOf(".");
		String suffix = fileName.substring(position);
		return formatDate +"_"+ random  + suffix;
	}
	
	
	public SRTPStoreFileHandler(Account account){
		this.account=account;
		//路径保存到根路径下
		
		StringBuffer buf = new StringBuffer(account.getUserName()).append(SRTPConstants.BACKSLASH);
        int level=account.getLevel();
        
        if (level > SRTPConstants.FOLDER_MAX_LEVEL){
        	  level =  SRTPConstants.FOLDER_MAX_LEVEL;
        }
        
        //产生文件夹
        Random r=new Random();
        for (int i = 0; i < level; i++) {
          buf.append(SRTPConstants.LETTER_AND_NUMBER_CHAR[r.nextInt(SRTPConstants.LETTER_AND_NUMBER_CHAR.length)]).append(SRTPConstants.BACKSLASH);
        }
        if (buf.charAt(0) == '/') {
           buf.deleteCharAt(0);
         }
        /**
         * 文件的保存
         */
        this.savePath = buf.toString();
        /**
         * 文件的完整路径
         */
        this.dirPath=this.account.getRootPath()+this.savePath;
        
        File dirFolder=new File(this.dirPath);
        //文件夹不存在则创建
        if(!dirFolder.exists()){
        	dirFolder.mkdirs();
        }
		//文件路径
		//this.savePath=this.savePath+this.fileName;
	}
	
	public SRTPResult process(SRTPParam reqParams){
		   //产生新的文件名
		FileUpload fileUpload=reqParams.getFileUpload();
		String srcFileName=reqParams.getFileName();
		log.info("--srcFileName--"+srcFileName);
		if(StringUtils.isBlank(srcFileName)){
			srcFileName=fileUpload.getFilename();
		}
		//生成新的文件名
        this.fileName=generateFileNameOfTime(srcFileName);
		SRTPResult result=new SRTPResult();
		result.setAction(reqParams.getAction());
		File newFile=new File(this.getRealSavePath());
		try {
			 boolean bool=fileUpload.renameTo(newFile);
			 result.setCode(bool);
			 result.setMsg("文件上传成功");
			 result.setFilePath(this.getSavePath());
			if( bool && reqParams.getThumbMark().equals(SRTPConstants.THUMB_MARK_YES)){
			   this.createThumb();
			}
			return result;
		} catch (IOException e) {
			e.printStackTrace();
			result.setCode(false);
			result.setMsg("存储文件报错"+e+",acount:"+account);
			log.error("存储文件报错"+e+",acount:"+account);
		}			
		
		return result;
	}
	/**
	 * 创建缩略图
	 */
	public void createThumb(){
		if(log.isDebugEnabled()){
			log.debug("生成缩略图");
		}
		String thumbFileName=SRTPThumbUtil.getThumbImagePath(fileName);
		SRTPThumbUtil.createThumbImage(new File(this.getRealSavePath()),new File(this.dirPath+thumbFileName),this.account.getThumbWidth(),this.account.getThumbHeight());
	 
	}
	

	/**
	 * 获取文件真实路径
	 * @return
	 */
	public String getRealSavePath(){
		return this.dirPath+this.fileName;
	}
	/**
	 * 获取访问路径
	 * @return
	 */
	public String getSavePath(){
		return this.savePath+this.fileName;
	}

}
